package com.example.casper.Experiment2024.gone;

import android.app.Application;
import android.content.Context;
import android.opengl.GLES20;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.casper.Experiment2024.items.Location;
import com.example.casper.Experiment2024.items.locationSave;

import java.util.List;

public class SharedViewModel extends AndroidViewModel {

    // OpenGL 资源
    public int textureId;

    // 持久化工具类
    private locationSave locationDataManager;

    // MutableLiveData 用于选中的省份
    private MutableLiveData<String> selectedProvince = new MutableLiveData<>();

    // LiveData 用于更新 Location 数据
    private final MutableLiveData<Location> locationUpdated = new MutableLiveData<>();
    private final MutableLiveData<Boolean> listRefreshNeeded = new MutableLiveData<>();

    public SharedViewModel(@NonNull Application application) {
        super(application);
        locationDataManager = new locationSave(application.getApplicationContext());
    }
    // 获取 ListFragment 刷新数据的 LiveData
    public LiveData<Boolean> getListRefreshNeeded() {
        return listRefreshNeeded;
    }
    // 获取更新的 Location 数据
    public LiveData<Location> getLocationUpdated() {
        return locationUpdated;
    }
    // 设置 ListFragment 需要刷新数据的方法
    public void setListRefreshNeeded() {
        listRefreshNeeded.postValue(true);
    }
    // 设置更新的 Location 数据并持久化
    public void setLocationUpdated(Location location) {
        // 异步处理存储和数据更新操作
        new Thread(() -> {
            // 读取现有的分享列表
            List<Location> sharedLocations = locationDataManager.readShareItems();

            // 将新位置添加到列表
            sharedLocations.add(location);

            // 保存更新后的分享列表
            locationDataManager.saveShareItems(sharedLocations);

            // 使用 postValue() 更新 LiveData，通知观察者
            locationUpdated.postValue(location);
        }).start();
    }


    // 获取当前选中的省份
    public LiveData<String> getSelectedProvince() {
        return selectedProvince;
    }

    // 设置选中的省份
    public void setSelectedProvince(String province) {
        selectedProvince.setValue(province);
    }

    // 释放 OpenGL 资源的地方
    public void onDestroy() {
        if (textureId != 0) {
            GLES20.glDeleteTextures(1, new int[]{textureId}, 0);
            textureId = 0;
        }
    }

}
